from configparser import ConfigParser
import os
import pymysql
class ConfigReader:
    def __init__(self,file_name):
        self.config = ConfigParser()
        config_path = os.path.split(os.path.realpath(__file__))[0] + os.sep + file_name
        # 读取文件信息
        self.config.read(config_path)
    def get_config(self,config_item):
        for section in self.config.sections():
            if self.config.has_option(section, config_item):
                return self.config.get(section,config_item)
class DB:
    def __init__(self,databse_name,cfg_obj = 'database_dev.cfg'): # 数据库名称
        database = ConfigReader(cfg_obj)   # 手动切换
        self.databse_name = databse_name
        self.host = database.get_config(databse_name + "_host")
        self.port = database.get_config(databse_name + "_port")
        self.user = database.get_config(databse_name + "_user")
        self.password = database.get_config(databse_name + "_password")
    def connect(self):
        self.db = pymysql.connect(host=self.host,user=self.user,password=self.password,port=int(self.port),database=self.databse_name,cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def search_one(self,sql):
        self.connect()
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
        except:
            self.db.rollback()
            result = 0
        self.close()
        return result
    def search_all(self,sql):
        self.connect()
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
        except:
            self.db.rollback()
            result = 0
        self.close()
        return result
    def __edit(self,sql):
        self.connect()
        try:
            self.cursor.execute(sql)
            self.db.commit()
            result = 1
        except:
            self.db.rollback()
            result = 0
        self.close()
        return result
    def insert(self,sql):
        return self.__edit(sql)
    def delete(self,sql):
        return self.__edit(sql)
    def update(self,sql):
        return self.__edit(sql)








